package com.example.thread.executordemo.demo1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ZhangLiang
 * @Date: 2021/07/09/10:42
 * @Description:
 */
public class ThreadPoolExecutorCallableDemo {

    /**
     * 核心线程数定义了最小可以同时运行的线程数量。
     */
    private static final int CORE_POLL_SIZE=5;

    /**
     * 线程池的最大线程数, 当队列中存放的任务达到队列容量的时候，当前可以同时运行的线程数量变为最大线程数
     */
    private static final int MAX_POOL_SIZE=10;

    /**
     * 任务队列，用来储存等待执行任务的队列
     */
    private static final int QUEUE_CAPACITY = 100;
    /**
     * 当线程数大于核心线程数时，多余的空闲线程存活的最长时间
     */
    private static final Long KEEP_ALIVE_TIME = 1L;

    public static void main(String[] args) {
        //使用阿里巴巴推荐的创建线程池的方式
        //通过ThreadPoolExecutor构造函数自定义参数创建
        ThreadPoolExecutor executor=new ThreadPoolExecutor(CORE_POLL_SIZE,MAX_POOL_SIZE,KEEP_ALIVE_TIME, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(QUEUE_CAPACITY),
                new ThreadPoolExecutor.CallerRunsPolicy());

        List<Future<String>> futures=new ArrayList<>();
        Callable<String> callable=new MyCallable();
        for (int i = 0; i < 10; i++) {
          Future<String> future=executor.submit(callable);
            futures.add(future);
        }
        for (Future<String> fut: futures
             ) {
            try {
                System.out.println(fut.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        //终止线程池
        executor.shutdown();
        while (!executor.isTerminated()){
//            System.out.println("还有线程未完成");
        }
        System.out.println("所有线程已经完成");
    }
}
